package ru.jexp.rcp.supply.editor;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IViewReference;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.forms.ManagedForm;
import org.eclipse.ui.part.EditorPart;

import ru.jexp.rcp.supply.n.form.IRowForm;
import ru.jexp.rcp.supply.n.form.Mode;

public abstract class AbstractEditorPart<RowFormT extends IRowForm> extends EditorPart
{
	protected abstract RowFormT createFormPart();
	
	protected abstract void updateViewPart(IViewPart view);
	
	private RowFormT rowForm;

	@Override
	public void doSave(IProgressMonitor monitor)
	{
		rowForm.save();

		updateViewPart();
		updateEditorInput();
		updateTitle();
		updateDirtyState();
	}

	@Override
	public void doSaveAs()
	{
	}

	public RowFormT getRowForm()
	{
		return rowForm;
	}

	@Override
	public void init(IEditorSite site, IEditorInput input) throws PartInitException
	{
		setSite(site);
		setInput(input);
		setPartName(input.getName());
		setTitleImage(input.getImageDescriptor().createImage());
	}

	@Override
	public boolean isDirty()
	{
		return rowForm != null && rowForm.isDirty();
	}

	@Override
	public boolean isSaveAsAllowed()
	{
		return false;
	}

	@Override
	public void createPartControl(Composite parent)
	{
		ManagedForm mf = new ManagedForm(parent)
		{
			public void dirtyStateChanged()
			{
				firePropertyChange(PROP_DIRTY);
			};
		};
		rowForm = createFormPart();
		rowForm.setFormInput(getEditorInput());
		mf.addPart(rowForm);
	}

	@Override
	public void setFocus()
	{
		rowForm.setFocus();
	}

	private void updateEditorInput()
	{
		EditorInputBean editorInput = (EditorInputBean) getEditorInput();
		editorInput.setMode(Mode.EDIT);
	}

	private void updateViewPart()
	{
		IViewReference[] viewReferences = getEditorSite().getPage().getViewReferences();
		for (IViewReference viewReference : viewReferences)
		{
			updateViewPart(viewReference.getView(false));
		}
	}
	
	private void updateTitle()
	{
		EditorInputBean editorInput = (EditorInputBean) getEditorInput();
		setPartName(editorInput.getName());
		firePropertyChange(PROP_TITLE);
	}
	
	private void updateDirtyState()
	{
		firePropertyChange(PROP_DIRTY);
	}

}
